package org.linuxsogood.chapter2.utils;

/**
 * Created by m on 16/3/19.
 */
public class CastUtils {
    public static int castInt(Object o) {
        return CastUtils.castInt(o,0);
    }

    public static int castInt(Object o, int defaultValue) {
        int value = defaultValue;
        if (o != null) {
            String s = castString(o);
            if (StringUtil.isNotEmpty(s)) {
                try {
                    int i = Integer.parseInt(s);
                } catch (NumberFormatException e) {
                    //
                    value = defaultValue;
                }
            }
        }
        return value;
    }

    public static String castString(Object object) {
        return CastUtils.castString(object, "");
    }

    public static String castString(Object object, String defaultValue) {
        String s = String.valueOf(object);
        return null == s ? defaultValue : s;
    }

    public static double castDouble(Object obj, double defaultValue) {
        double value = defaultValue;
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    value = Double.parseDouble(strValue);
                } catch (NumberFormatException e) {
                    value = defaultValue;
                }
            }
        }
        return value;
    }

    public static long castLong(Object obj, long defaultValue) {
        long value = defaultValue;
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    value = Long.parseLong(strValue);
                } catch (NumberFormatException e) {
                    value = defaultValue;
                }
            }
        }
        return value;
    }

    public static long castLong(Object object) {
        return castLong(object, 0);
    }

}
